package cn.zyx.config.shiro;

import cn.zyx.common.enums.LogType;
import cn.zyx.common.properites.GlobalProperties;
import cn.zyx.common.utils.ServletsUtils;
import cn.zyx.common.utils.sys.JWTUtils;
import cn.zyx.common.utils.sys.SpringContextHolderUtils;
import cn.zyx.common.utils.sys.UserUtils;
import cn.zyx.common.utils.sys.log.LogUtils;
import cn.zyx.sys.entity.AccessKey;
import cn.zyx.sys.entity.Menu;
import cn.zyx.sys.entity.Role;
import cn.zyx.sys.entity.User;
import cn.zyx.sys.service.AccessKeyService;
import cn.zyx.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.Servlet;
import java.util.Collection;
import java.util.List;

/**
 * 自定义系统安全认证实现类
 */
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private UserService userService;

    private AccessKeyService accessKeyService;

    /**
     * 必须重写此方法，不然Shiro会报错
     * 让shiro支持我们自定义的token，即如果传入的token是JWTToken则放行
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 认证回调函数, 登录时调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        logger.debug("doGetAuthenticationInfo:  认证 start {}",authenticationToken);
        // 获取token
        String token = (String) authenticationToken.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String loginName = JWTUtils.getLoginName(token);
        if (loginName == null) {
            throw new AuthenticationException("无效的token");
        }

        // 校验用户
        User user = getUserService().getUserByLoginName(loginName);
        // 检验是否是第三方系统访问
        AccessKey accessKey = getAccessKeyService().getInfoByAccessKeyId(loginName);
        if (user == null && accessKey == null) {
            throw new AuthenticationException("用户不存在......");
        }

        if (JWTUtils.verify(token) == 1) {
            throw new AuthenticationException("token已经过期");
        } else if (JWTUtils.verify(token) == 2) {
            throw new AuthenticationException("用户名或者密码错误");
        }

//		return new SimpleAuthenticationInfo(token, token, "my_realm");
        // 校验登录验证码
//		if ( LoginController.isValidateCodeLogin(token.getLoginName(), false, false)){
//			Session session = UserUtils.getSession();
//			String code = (String)session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
//			if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)){
//				throw new AuthenticationException("msg:验证码错误, 请重试.");
//			}
//		}

        // 校验用户名密码
        if (user != null && GlobalProperties.NO.equals(user.getLoginFlag())){
            throw new AuthenticationException("该已帐号禁止登录.");
        }
        if (accessKey != null && GlobalProperties.NO.equals(accessKey.getIsActive())){
            throw new AuthenticationException("该accessKey已被禁止登录.");
        }
        // byte[] salt = Encodes.decodeHex(user.getPassword().substring(0,16));
        return new SimpleAuthenticationInfo(token, token, getName());
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.debug("doGetAuthorizationInfo: 授权 start {} ",principals);
        String username = JWTUtils.getLoginName(principals.toString());
        // 获取当前已登录的用户
        User user = getUserService().getUserByLoginName(username);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            List<Menu> list = UserUtils.getMenuList();
            for (Menu menu : list){
                if (StringUtils.isNotBlank(menu.getPermission())){
                    // 添加基于Permission的权限信息
                    for (String permission : StringUtils.split(menu.getPermission(),",")){
                        info.addStringPermission(permission);
                    }
                }
            }
            // 添加用户权限
            info.addStringPermission("user");
            // 添加用户角色信息
            for (Role role : user.getRoleList()){
                info.addRole(role.getEnname());
            }
            // 更新登录IP和时间
            getUserService().updateUserLoginInfo(user);
            // 记录登录日志
            LogUtils.saveLog(ServletsUtils.getRequest(), "系统登录", LogType.LOGIN.getType());
            return info;
        } else {
            // 获取accessKey的权限信息
            //AccessKey accessKey = getAccessKeyService().getInfoByAccessKeyId(username);
            return null;
        }
    }

    @Override
    protected void checkPermission(Permission permission, AuthorizationInfo info) {
        logger.debug("checkPermission {} {}",permission,info);
        authorizationValidate(permission);
        super.checkPermission(permission, info);
    }

    @Override
    protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info) {
        logger.debug("isPermitted[] {} {}" ,permissions,info);
        if (permissions != null && !permissions.isEmpty()) {
            for (Permission permission : permissions) {
                authorizationValidate(permission);
            }
        }
        return super.isPermitted(permissions, info);
    }

    @Override
    public boolean isPermitted(PrincipalCollection principals, Permission permission) {
        logger.debug("isPermitted {} {}" ,permission,principals);
        authorizationValidate(permission);
        return super.isPermitted(principals, permission);
    }

    @Override
    protected boolean isPermittedAll(Collection<Permission> permissions, AuthorizationInfo info) {
        logger.debug("isPermittedAll {} {}" ,permissions,info);
        if (permissions != null && !permissions.isEmpty()) {
            for (Permission permission : permissions) {
                authorizationValidate(permission);
            }
        }
        return super.isPermittedAll(permissions, info);
    }

    @Override
    public String getAuthorizationCacheName() {
        logger.debug("getAuthorizationCacheName {} " ,this.getClass().getSimpleName());
        return this.getClass().getSimpleName();
    }

    /**
     * 授权验证方法
     * @param permission
     */
    private void authorizationValidate(Permission permission){
        // 模块授权预留接口
    }

    /**
     * 获取系统业务对象
     */
    public UserService getUserService() {
        if (userService == null){
            userService = SpringContextHolderUtils.getBean(UserService.class);
        }
        return userService;
    }

    public AccessKeyService getAccessKeyService() {
        if (accessKeyService == null){
            accessKeyService = SpringContextHolderUtils.getBean(AccessKeyService.class);
        }
        return accessKeyService;
    }
}
